#!/usr/bin/python
# -*- coding : UTF-8 -*-
# ========================
# @Time  : 2020/5/18 10:07
# @Author: Mecell
# @File  : conftest.py
# ========================
import os
import pytest
import allure

from common.config_packaging import config_obj
from common.mysql_packaging import MysqlHandle
from common.context_packaging import ContextHandle
from common.request_packaging import HttpRequest
from common.log_packaging import logger
from common.path_constants import EXPORT_DIR



@allure.step("前置条件：创建HTTP请求会话")
def create_session():
    request_obj = HttpRequest()
    logger.info('{:=^50s}'.format("创建HTTP请求会话"))
    return request_obj

@allure.step("后置处理：关闭HTTP请求会话")
def close_session(request_obj):
    request_obj.close_session()
    logger.info('{:=^50s}'.format("关闭HTTP请求会话"))

@allure.step("前置条件：创建MySQL连接")
def create_mysql():
    mysql_obj = MysqlHandle()
    logger.info('{:=^54s}\n'.format("创建MySQL连接"))
    return mysql_obj

@allure.step("后置处理：关闭MySQL连接")
def close_mysql(mysql_obj):
    mysql_obj.close_sql()
    logger.info('{:=^54s}\n\n'.format("关闭MySQL连接"))

@allure.step("后置处理：清空文件夹")
def clear_file():
    try:
        for filename in os.listdir(EXPORT_DIR):
            file = os.path.join(EXPORT_DIR, filename)
            if os.path.exists(file) and os.path.isfile(file):
                os.remove(file)
                logger.info('清空文件夹成功!')
    except Exception as err:
        logger.exception(f'清空文件夹失败!,异常信息为:{err}\n')


@pytest.fixture(scope='class')
def init_env():
    request_obj = create_session()
    mysql_obj = create_mysql()
    yield request_obj, mysql_obj
    close_session(request_obj)
    close_mysql(mysql_obj)


@pytest.fixture(scope='class')
def init_env_clear():
    request_obj = create_session()
    mysql_obj = create_mysql()
    yield request_obj, mysql_obj
    close_session(request_obj)
    close_mysql(mysql_obj)
    clear_file()